/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { DfuDeviceSelector } from './DfuDeviceSelector'
import ble from '@ohos.bluetooth.ble';
import hilog from '@ohos.hilog';

export class DfuDefaultDeviceSelector extends DfuDeviceSelector {
  private TAG: string = 'DfuDefaultDeviceSelector';
  private DOMAIN: number = 0x8632;

  public matches(device: ble.ScanResult, rssi: number, scanRecord: Uint8Array,
    originalAddress: string, incrementedAddress: string, oriname: string): boolean {
    hilog.info(this.DOMAIN, this.TAG,
      `matches: ${JSON.stringify(device)}, oriAddr:${originalAddress}, incAddr:${incrementedAddress}`);

    //TODO: For HOS Next, when changed to bootloader mode, address will change
    //Temporary solution is for this device: the incomplete uuid is 0xFE59, so can use it to find device
    //other solution is the name change to boot, in this case need to use the former name to check both the
    //head of device name and tail of device name.
    let startChar: string = oriname.slice(3);
    let isStartWithOriname: boolean = device.deviceName.startsWith(startChar);
    let endChar: string = 'Boot';
    let isEndWithOriname: boolean = device.deviceName.endsWith(endChar);
    let rawBuf: Uint8Array = new Uint8Array(device.data);
    let hexStr: string = '';
    for (const ditem of rawBuf) {
      let hexItem: string = ditem.toString(16);
      hexStr += hexItem;
    }
    hilog.info(this.DOMAIN, this.TAG, `matches hexStr: ${hexStr}`);
    let isBootUUID: Boolean = hexStr.toUpperCase().includes('59FE');
    hilog.info(this.DOMAIN, this.TAG, `matches res: isSWO[${isStartWithOriname}],isEWO[${isEndWithOriname}]`+
      `isBUID:[${isBootUUID}]`);
    if (originalAddress === device.deviceId || incrementedAddress === device.deviceId) {
      return true;
    } else if (isStartWithOriname && isEndWithOriname && isBootUUID) {
      return true;
    }
    return false;
  }
}